package com.fangs.yehwangglobal.widget.loading;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.fangs.yehwangglobal.R;


/**
 * Created by ivan.cai on
 * 公共显示加载框
 */
public class LoadIngDialog extends Dialog {

    private final Handler mHandler = new Handler();
    private final Runnable mRummable = () -> {
        if (getContext() == null || ((getContext() instanceof Activity)
                && ((Activity) getContext()).isFinishing())) return;

        try {
            if (isShowing()) {
                dismiss();
            } else {
                show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    };

    public LoadIngDialog(@NonNull Context context) {
        super(context, R.style.transparent_dialog);
        setCanceledOnTouchOutside(false);
        setOnCancelListener(dialog -> Toast.makeText(context, "cancel", Toast.LENGTH_SHORT).show());
        setContentView(LayoutInflater.from(context).inflate(R.layout.loging_dialog_layout, null),
                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    }

    public void showNow() {
        mHandler.removeCallbacks(mRummable);
        if (!isShowing()) {
            mHandler.postDelayed(mRummable, 500);
        }
    }

    public void dismissNow() {
        mHandler.removeCallbacks(mRummable);
        if (isShowing()) {
            mHandler.postDelayed(mRummable, 500);
        }
    }

}

